import java.util.HashMap;
import java.util.Map;

public class Solution {
    public String fractionToDecimal(int numerator, int denominator) {
        // 处理特殊情况
        if (denominator == 0) {
            throw new IllegalArgumentException("Denominator cannot be zero.");
        }
        if (numerator == 0) {
            return "0";
        }

        // 转换为长整型，避免溢出
        long numeratorLong = (long) numerator;
        long denominatorLong = (long) denominator;

        // 判断结果的符号
        StringBuilder result = new StringBuilder();
        if (numeratorLong < 0 ^ denominatorLong < 0) {
            result.append("-");
        }

        // 取绝对值
        numeratorLong = Math.abs(numeratorLong);
        denominatorLong = Math.abs(denominatorLong);

        // 计算整数部分
        long integerPart = numeratorLong / denominatorLong;
        result.append(integerPart);

        // 计算余数
        long remainder = numeratorLong % denominatorLong;
        if (remainder == 0) {
            return result.toString();
        }

        // 添加小数点
        result.append(".");

        // 用于存储余数及其对应的索引
        Map<Long, Integer> remainderIndexMap = new HashMap<>();
        StringBuilder fractionPart = new StringBuilder();

        // 计算小数部分
        while (remainder != 0 && !remainderIndexMap.containsKey(remainder)) {
            remainderIndexMap.put(remainder, fractionPart.length());
            remainder *= 10;
            fractionPart.append(remainder / denominatorLong);
            remainder %= denominatorLong;
        }

        // 如果有循环节
        if (remainder != 0) {
            int index = remainderIndexMap.get(remainder);
            fractionPart.insert(index, "(");
            fractionPart.append(")");
        }

        result.append(fractionPart);

        return result.toString();
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        System.out.println(solution.fractionToDecimal(1, 2)); // 输出: "0.5"
    }
}